package cn.gx.kevin.controller;

import cn.gx.kevin.common.ui.AdminControllerHelper;
import cn.gx.kevin.common.user.LoginUser;
import cn.gx.kevin.common.utils.DateUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import cn.gx.kevin.common.annotation.ApiDescript;
import cn.gx.kevin.common.annotation.ApiParams;
import cn.gx.kevin.common.annotation.ApiParamsDesc;
import cn.gx.kevin.common.annotation.ApiReturnDesc;
import cn.gx.kevin.common.ui.AjaxResult;
import cn.gx.kevin.common.ui.ClientButton;
import cn.gx.kevin.common.ui.DataGrid;
import cn.gx.kevin.domain.Org;
import cn.gx.kevin.service.IOrgService;
import cn.gx.kevin.controller.ResetfulBaseController;
import cn.gx.kevin.service.IBaseService;
import com.github.pagehelper.util.StringUtil;
import net.sf.jsqlparser.statement.execute.Execute;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Generate by Kevin's CodeBuilder
 **/
@ApiDescript("系统机构模块")
@Controller
@RequestMapping(value = "/org")
public class OrgController extends ResetfulBaseController<Org, String> {

    IOrgService orgService;

    @Resource(name = "orgService")
    @Override
    public void setService(IBaseService<Org, String> service) {
        this.service = service;
        orgService = (IOrgService)service;
    }

    @Override
    @RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
        if ("tree".equals(pageName)) {
            request.setAttribute("gridid", "org");
            AjaxResult json = this.query(request);
            request.setAttribute("treeJson", ((JSONArray)json.data).toJSONString());
        }else if("form".equals(pageName) || "index".equals(pageName)){
            String pid = request.getParameter("pid");
            if(StringUtils.isEmpty(pid)){
                pid = "0";
            }
            request.setAttribute("pid",pid);
        }
        return super.page(pageName, request);
    }

    /*
     * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id'}")
    @ApiDescript("根据ID查询数据")
    @ApiParams("{'id':''}")
    @Override
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public @ResponseBody AjaxResult get(String id) throws Exception {
        return super.get(id);
    }

    @Override
    @ApiDescript("新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody AjaxResult add(HttpServletRequest request) throws Exception {
        return super.add(request);
    }

    @ApiDescript("更新")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody AjaxResult update(HttpServletRequest request) throws Exception {
        return super.update(request);
    }

    @ApiDescript("删除")
    @ApiParams("{'idList':'id1,id2'}")
    @RequestMapping(value = "/delete")
    public @ResponseBody AjaxResult delete(HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");
        boolean delAll = StringUtils.isNotEmpty(request.getParameter("delAll"));
        orgService.deleteOrg(id,delAll);
        return returnSuccess();
    }


    @ApiDescript("加载所有子机构id")
    @ApiParams("{'pid':'pid'}")
    @RequestMapping(value = "/getAllIdByPid")
    public @ResponseBody AjaxResult getAllIdByPid(HttpServletRequest request) throws Exception {
        String pid = request.getParameter("pid");
        List<List<String>> rest = orgService.getAllChildsIdByPid(pid);
        return returnSuccData(rest);
    }
    


	@ApiDescript("分页多条件可排序查询")
    @ApiParams("{'page':1,'pageSize':15,'_col_sort_fieldName':'asc','pid':''}")
    @ApiParamsDesc("{page:'当前页',pageSize:'页大小',_col_sort_fieldName:'desc/asc，_col_sort_为前缀标志，fieldName为需要排序的字段名','pid':'父机构id'}")
    @RequestMapping(value = "/list")
    public @ResponseBody AjaxResult list(HttpServletRequest request) throws Exception {
        return super.list(request);
    }

    @Override
    public void buttonCreateHanlder(Org bean, ClientButton button) {
        if (bean != null) {
            if ("0".equals(bean.getPid())) {
                if ("lineAddFn".equals(button.getHandler())) {
                    button.setVisualable(false);
                }
                if (bean.getOrgType().equals(0) && "lineChildFn".equals(button.getHandler())) {
                    button.setVisualable(false);
                }
            } else if ("lineChildFn".equals(button.getHandler())) {
                button.setVisualable(false);
            }
        }
    }

    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        String pid = request.getParameter("pid");
        params.put("pid", pid);
        String keywords = request.getParameter("keywords");
        if(StringUtils.isNotEmpty(keywords)){
            params.put("keywords", keywords);
        }
        return params;
    }

    @Override
    @ApiDescript("根据pid返回树形json，每次返回两级数据")
    @ApiParams("{'pid':'','deep':'1'}")
    @ApiParamsDesc("{'pid':'父机构id','deep':'向下查询的深度'}")
    @RequestMapping(value = "/query")
    public @ResponseBody AjaxResult query(HttpServletRequest request) throws Exception {
        String pid = request.getParameter("pid");
        if (StringUtils.isEmpty(pid)) {
            pid = "0";
        }
        List<ClientButton> buttonlist;
        DataGrid grid = getDataGridCfg(request);
        if (grid != null) {
            buttonlist = grid.getLineButton();
        } else {
            buttonlist = new ArrayList<ClientButton>();
        }
        for(ClientButton button : buttonlist){
            if(!this.hasDataPrivilage(null,request,button.getCmd())){
                button.setDisabled(true);
                button.setParams("unAuthor", "1");
            }
        }
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, String> order = new HashMap<String, String>();
        order.put("orderIndex", "asc");
        param.put("orderColumn", order);
        if(request.getParameter("all") != null){
            param.put("query_all",true);
        }
        int deep = 1;
        String deepStr = request.getParameter("deep");
        if(StringUtils.isNotEmpty(deepStr)){
            deep = Integer.valueOf(deepStr);
        }
        JSONArray array = orgService.getOrgJsonByPid(pid, buttonlist, param,deep);
        return this.returnSuccData(array);
    }

    @Override
    public Map<String, Object> setQueryParams(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        String pid = request.getParameter("pid");
        params.put("pid", pid);
        return params;
    }

    @ApiDescript("返回登录用户机构及下属机构")
    @ApiParams("{'':'','':''}")
    @ApiParamsDesc("{'':'','':''}")
    @RequestMapping(value = "getUserOrgs")
    public  @ResponseBody AjaxResult getUserOrgs(HttpServletRequest request, HttpServletResponse response) throws Exception {
        AjaxResult ajaxResult = new AjaxResult(0,"");
        String pid = request.getParameter("pid");
        if(StringUtils.isEmpty(pid)){
            LoginUser user = this.getLoginUser();
            if(user.isSuperAdmin()){
                pid = "0";
            }else{
                pid = user.getOrgId();
            }
        }
        JSONArray array = orgService.getOrgJsonByPid(pid);
        return this.returnSuccData(array);
    }



    @RequestMapping(value = "export")
    public  void exportOrg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.setDownLoadFlag(request);
        Map<String,Object> params = new HashMap<>();
        String pid = request.getParameter("pid");
        if(StringUtils.isNotEmpty(pid)){
            List<Org> roots = this.orgService.getRootOrgs();
            if(roots.size() == 1){
                Org root =  roots.get(0);
                if(!root.getId().equals(pid)){
                    params.put("expid",pid);
                }
            }else{
                params.put("expid",pid);
            }
        }
        String fileName = DateUtils.formatCurrentDateTime("yyyyMMddHHmmss")+ "机构列表.xlsx";
        String file = this.createDir("tmp",request)  + fileName;
        File tmpFile = new File(file);
        OutputStream fileOutputStream = null;
        try{
            tmpFile.createNewFile();
            fileOutputStream = new FileOutputStream(tmpFile);
            this.orgService.exportOrgs(fileOutputStream,params);
            FileInputStream inputStream = new FileInputStream(tmpFile);
            AdminControllerHelper.responseFile(response,"机构列表.xlsx","application/msexcel",inputStream);
            this.clearDownLoadFlag(request);
        }catch (Exception x){
            logger.error("{}",x);
            AdminControllerHelper.responseJson(response,1,"导出失败！",null);
        }finally {
            if(fileOutputStream != null){
                try{
                    fileOutputStream.close();
                }catch (Exception x){}
            }
            FileUtils.deleteQuietly(tmpFile);
        }

    }

    @RequestMapping(value = "import")
    public @ResponseBody AjaxResult importOrg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pid = request.getParameter("pid");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile xlsFile = fileMap.get("attachments");
        String rootCode = request.getParameter("rootCode");
        long count =  this.orgService.importOrgs(xlsFile,rootCode, pid);
        return returnSuccMsg("成功导入:"+count);
    }
}
